<template>
	<el-dialog
		:close-on-click-modal="false"
		:close-on-press-escape="true"
		:title="title"
		v-model="isVisible"
		destroy-on-close
		width="80%"
		:align-center="true"
		@close="close"
	>
		<div class="formBox">
			<el-form ref="ruleFormRef" :model="data.form" label-position="top" label-width="100px" :rules="data.rules">
				<el-form-item label="所属组织">
					<el-alert type="warning" :closable="false" v-if="data.form.deptId">
						<span>{{ data.form.deptName }}</span>
					</el-alert>
					<el-tree-select
						v-else
						v-model.number="data.form.deptId"
						:data="treeData"
						style="width: 100%"
						:props="{
							value: 'deptId',
							children: 'children',
							label: 'deptName',
						}"
						default-expand-all
						check-strictly
						:render-after-expand="false"
						emptyText="no data"
						@node-click="handleNodeClick"
					/>
				</el-form-item>

				<el-form-item label="小区地址" prop="address">
					<el-input v-model="data.form.address" type="textarea" />
				</el-form-item>
				<el-form-item label="小区名称" prop="name">
					<el-input v-model="data.form.name" type="textarea" />
				</el-form-item>
				<el-form-item label="粘贴经纬度" prop="lnglat">
					<el-input v-model="data.form.lnglat" />
				</el-form-item>

				<el-form-item label="经度" prop="longitude">
					<el-input disabled v-model="data.form.longitude" />
				</el-form-item>
				<el-form-item label="纬度" prop="latitude">
					<el-input disabled v-model="data.form.latitude" />
				</el-form-item>
			</el-form>
			<div class="rightBox">
				<a class="picker" target="_blank" href="https://lbs.amap.com/tools/picker">高德地图坐标拾取器</a>
				<div id="map"></div>
				<!-- <div class="searchBar">
					<input
						:ref="setRefs('tipinput')"
						v-model="data.mapSearchKey"
						id="tipinput"
						type="text"
						class="el-input"
						placeholder="请输入小区关键字"
					/>
				</div> -->
			</div>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button plain type="warning" @click="close"> 取消 </el-button>
				<el-button plain type="primary" @click="submit(ruleFormRef)"> 确定 </el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup name="EquipmentEdit">
import { reactive, onMounted, ref, computed, onBeforeUnmount, onUnmounted, watch } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import AMapLoader from '@amap/amap-jsapi-loader';
import { shallowRef } from 'vue';
import communityApi from '/@/api/smoke/community';

// (window as any)._AMapSecurityConfig = {
// 	securityJsCode: 'c2706fea1fa98c6aa7e058393af8f312',
// };

const ruleFormRef = ref<FormInstance>();
const value = ref(11);

const validateLnglat = (rule: any, value: any, callback: any) => {
	if (value) {
		let lnglat = value.split(',');
		if (lnglat.length == 2) {
			console.log(lnglat);

			// 纬度正则表达式(-90 至 90)：
			let latReg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/;

			//经度正则表达式（-180 至 180）：
			let longReg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/;

			if (longReg.test(lnglat[0]) && latReg.test(lnglat[1])) {
				data.form.longitude = lnglat[0];
				data.form.latitude = lnglat[1];
				callback();
			} else {
				callback(new Error('经纬度格式不正确！'));
			}
		}
		callback(new Error('经纬度格式不正确！'));
	} else {
		callback();
	}
};
// data
const data = reactive({
	mapSearchKey: '',
	form: {
		lnglat: '',
		address: '',
		name: '',
		latitude: '',
		longitude: '',
		deptId: '',
		deptName: '',
	},
	rules: {
		address: [{ required: true, message: '请输入小区地址', trigger: 'change' }],
		name: [{ required: true, message: '请输入小区名称', trigger: 'change' }],
		lnglat: [{ validator: validateLnglat, trigger: 'change' }],
		longitude: [{ required: true, message: '请输入纬度', trigger: 'change' }],
		latitude: [{ required: true, message: '请输入纬度', trigger: 'change' }],
	},
});

// props
const props = defineProps({
	dialogVisible: {
		type: Boolean,
		default: false,
	},
	type: {
		type: String,
		default: 'add',
	},
	dept: {
		type: Object,
		default: () => {
			return {};
		},
	},
	treeData: {
		type: Array,
		default: function () {
			return [];
		},
	},
});

defineExpose({
	initForm,
	initMap,
});

let isVisible = computed(() => {
	return props.dialogVisible;
});

// emit
const emit = defineEmits(['close', 'success']);

const title = computed(() => {
	return props.type == 'add' ? '新增' : '修改';
});

function initForm(row: any) {
	if (row) {
		if (row.deptId == 0) row.deptId = '';
		data.form = row;
	} else {
		const { dept } = props;
		data.form = {
			lnglat: '',
			address: '',
			name: '',
			latitude: '',
			longitude: '',
			deptId: '',
			deptName: '',
		};
	}
}

// 对话框关闭
function close() {
	emit('close');
	ruleFormRef.value?.resetFields();
	data.mapSearchKey = '';
	// map.destroy();
}

// 新增
function add() {
	communityApi.addCommunity(data.form).then((res) => {
		ElMessage.success('新增成功');
		emit('success');
		ruleFormRef.value?.resetFields();
		// data.isVisible = false;
	});
}

// 修改
function update() {
	communityApi.updateCommunity(data.form).then((res) => {
		ElMessage.success('更新成功');
		emit('success');
		ruleFormRef.value?.resetFields();
		// data.isVisible = false;
	});
}

// 节点单击事件
const handleNodeClick = (data1: any) => {
	data.form.deptName = data1.deptName;
};

async function submit(formEl: FormInstance | undefined) {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (props.type === 'add') {
				add();
			} else {
				update();
			}
		} else {
			console.log('error submit!', fields);
		}
	});
}

let map: any = shallowRef(null);
let markerList: any[] = [];
let pAMap: any = null;
// 初始化地图
function initMap(LngLat?: [any, any]) {
	AMapLoader.load({
		key: '083c95b905d7722dbd4a5c96af81885c',
		version: '2.0',
		plugins: ['AMap.Scale', 'AMap.Geolocation', 'AMap.PlaceSearch', 'AMap.ToolBar', 'AMap.AutoComplete', 'AMap.CitySearch'],
	})
		.then((AMap) => {
			pAMap = AMap;
			map.value = new AMap.Map('map', {
				zoom: 16,
				center: LngLat ? LngLat : [104.066422, 30.658871],
				dragEnable: true,
				scrollWheel: true,
				doubleClickZoom: true,
				keyboardEnable: true,
			});
			map.value.setDefaultCursor('pointer');
			map.value.addControl(new AMap.Scale());
			map.value.addControl(new AMap.ToolBar());
			map.value.addControl(new AMap.Geolocation());

			// 地图搜索
			// mapSearch();

			// 如果编辑传递的有经纬度，显示出来marker
			showEditMarker(LngLat);

			// 保存当前点击的经纬度
			getLnglatByMapClick();
		})
		.catch((e: any) => {
			console.log(e);
		});
}

function getCurCity() {
	return new Promise((resolve, reject) => {
		map.value.getCity(function (info: any) {
			resolve(info.city);
		});
	});
}

// mapSearch
let placeSearch: any;
async function mapSearch() {
	let city = (await getCurCity()) || '成都';
	// 自动搜索
	pAMap.plugin('AMap.Autocomplete', function () {
		var autoOptions = {
			city: city,
			// input: refs.tipinput
			// output:refs.uo
		};
		var autoComplete = new pAMap.Autocomplete(autoOptions);
		autoComplete.on('select', selectSite);
	});

	// 地点搜索
	// pAMap.plugin(["AMap.PlaceSearch"], function () {
	// 	placeSearch = new pAMap.PlaceSearch({
	// 		pageSize: 5, // 单页显示结果条数
	// 		pageIndex: 1, // 页码
	// 		city: city, // 兴趣点城市
	// 		citylimit: true, //是否强制限制在设置的城市内搜索
	// 		map: map, // 展现结果的地图实例
	// 		// panel: refs.tipinput, // 结果列表将在此容器中进行展示。
	// 		panel: 'panel', // 结果列表将在此容器中进行展示。
	// 		autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
	// 	});
	// });
}

function doMapSearch() {
	placeSearch.search(data.mapSearchKey);
}

// 如果编辑有经纬度，显示marker
function showEditMarker(LngLat: any) {
	if (LngLat) {
		const [lng, lat] = LngLat;
		if (lng && lat) {
			let marker = new pAMap.Marker({
				position: LngLat,
			});
			markerList.push(marker);
			map.value.add(marker);
		}
	}
}

// 搜索后select
function selectSite(e: any) {
	let lngLat = [e.poi.location.lng, e.poi.location.lat];
	map.value.panTo(lngLat);
	let marker = new pAMap.Marker({
		position: lngLat,
	});
	marker.setMap(map);
	markerList.push(marker);
	if (!data.form.longitude) {
		data.form.longitude = e.poi.location.lng;
	}
	if (!data.form.latitude) {
		data.form.latitude = e.poi.location.lat;
	}
	if (!data.form.address) {
		data.form.address = e.poi.address;
	}
	if (!data.form.name) {
		data.form.name = e.poi.name;
	}
	// console.log(e);
}

// 点击地图，获取点击的经纬度
function getLnglatByMapClick() {
	map.value.on('click', function (e: any) {
		// 移除已创建的 marker
		data.form.longitude = e.lnglat.getLng();
		data.form.latitude = e.lnglat.getLat();

		let marker = new pAMap.Marker({
			position: [e.lnglat.getLng(), e.lnglat.getLat()],
		});
		map.value.remove(markerList);
		map.value.add(marker);
		markerList.push(marker);
	});
}
onMounted(() => {});
</script>
<style>
.amap-sug-result {
	z-index: 10240 !important;
}
</style>
<style lang="scss" scoped>
.formBox {
	display: grid;
	grid-template-columns: 300px 1fr;
	gap: 20px;
}

.rightBox {
	position: relative;
}

#map {
	width: 100%;
	height: 680px;
	position: relative;
}

:deep {
	.amap-copyright {
		opacity: 0;
	}

	.amap-logo {
		display: none;
		opacity: 0 !important;
	}

	.amap-geolocation {
		bottom: 95px !important;
		right: 19px !important;
	}
}

.searchBar {
	padding: 10px;
	left: 10px;
	top: 10px;
	position: absolute;
	border-radius: 5px;
	background-color: white;
	width: auto;
	min-width: 200px;

	input {
		width: 100%;
		height: 30px;
		line-height: 30px;
		padding: 0 10px;
	}
}

.picker {
	position: absolute;
	top: 5px;
	right: 5px;
	display: block;
	z-index: 10000;
	margin-bottom: 10px;
	background-color: #fff;
	padding: 5px 10px;
	text-decoration: none;
	color: #f00;
}
</style>
